package me.shurufa.activities;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.SparseArray;

import me.shurufa.R;
import me.shurufa.fragments.BookCatalogFragment;
import me.shurufa.fragments.BookInfoFragment;
import me.shurufa.fragments.BookMostCommentFragment;
import me.shurufa.fragments.BookMostDigestFragment;

/**
 * 作者 : andy
 * 日期 : 16/3/22 14:37
 * 邮箱 : andyxialm@gmail.com
 * 描述 :
 */
public class UserCenterActivity extends AppCompatActivity {

    private SparseArray<Fragment> fragments = new SparseArray<Fragment>(2);
    // 选中的菜单索引 默认是第0个
    private int mSelectedMenuIndex = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_user_center);
        initViews();
    }

    private void initViews() {
        switchFragment(mSelectedMenuIndex, true); // 默认第0页
    }

    public void switchFragment(int index, boolean force){
        if (mSelectedMenuIndex == index && ! force) {
            return;
        }
        Fragment oldFragment = fragments.get(mSelectedMenuIndex);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        if (oldFragment != null)
            ft.hide(oldFragment);

        mSelectedMenuIndex = index;
        Fragment newFragment = fragments.get(mSelectedMenuIndex);
        if (newFragment == null) {
            switch (mSelectedMenuIndex) {
                case 0: // 最多书评
                    newFragment = BookInfoFragment.newInstance(3658);
                    break;
                case 1: // 最多书摘
                    newFragment = BookInfoFragment.newInstance(3658);
                    break;
            }
            fragments.put(mSelectedMenuIndex, newFragment);
        }
        if (newFragment != null) {
            if (!newFragment.isAdded()) {
                ft.add(R.id.fragment_container, newFragment, String.valueOf(mSelectedMenuIndex));
            }
            ft.show(newFragment);
        }
        ft.commitAllowingStateLoss();
    }
}
